﻿using FlaUI.Core.AutomationElements;
using FlaUI.Core.Definitions;
using FlaUI.Core.Input;
using FlaUI.Core.WindowsAPI;
using FlaUI.UIA3.Patterns;
using LVYAN.Model;
using LVYAN.Model.AutoMation;
using LVYAN.Service;
using LVYAN.Service.AIAPI;
using LVYAN.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace Win
{
    /// <summary>
    /// 
    /// </summary>
    public static class WechatAuto
    {
        /// <summary>
        /// 处理反馈的消息让其有序号
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string OptMessage(string message)
        {
            if (string.IsNullOrWhiteSpace(message)) return "";
            if (message.Length < 50) return message;

            List<string> List = new List<string>();
            var messageArray = message.Split('。');
            if (messageArray.Count() > 1)
            {
                for (int i = 0; i < messageArray.Length; i++)
                {

                    if (!string.IsNullOrWhiteSpace(messageArray[i]))
                    {
                        List.Add($"{i + 1}.{messageArray[i]}");
                    }
                }
                return string.Join("。\n", List);
            }
            return message;
        }
        public static void PrintElement(this AutomationElement window)
        {
            Thread.Sleep(2000);
            foreach (var item in window.FindAllDescendants())
            {
                if (!string.IsNullOrWhiteSpace(item.Name))
                {
                    Console.WriteLine($"item.Name:{item.Name},{item.ControlType},item.Parent?.Name:{item.Parent?.Name},{item.Parent?.ControlType}");
                    var AllText = item.FindAllByXPath("//*/Text");
                    Console.WriteLine("AllText" + string.Join(',', AllText.Select(t => t.Name)));

                }



            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void PrintWindow(this Window window)
        {
            Thread.Sleep(2000);
            window = new MainWindow().GetWindowById();
            foreach (var item in window.FindAllDescendants())
            {
                if (!string.IsNullOrWhiteSpace(item.Name))
                    Console.WriteLine($"item.Name:{item.Name},{item.ControlType},item.Parent?.Name:{item.Parent?.Name},{item.Parent?.ControlType}");
            }
        }
        /// <summary>
        /// 设置内容 
        /// </summary>
        /// <param name="Message"></param>
        /// <param name="IsText">是否为文本</param>
        public static void SetText(string Message, bool IsText)
        {
            if (IsText)
            {
                Clipboard.SetDataObject(Message, true, 10, 200);
                //Clipboard.SetText(Message);
                Keyboard.TypeSimultaneously(new[] { VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_V });
            }
            else
            {
                try
                {
                    SendKeys.SendWait(Message);
                }
                catch (Exception)
                {
                    Clipboard.SetDataObject(Message, true, 10, 200);
                    Keyboard.TypeSimultaneously(new[] { VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_V });
                }
            }

        }
        /// <summary>
        /// 清空并赋值
        /// </summary>
        public static void ClearEditTextBoxUsingKeyboard(AutomationElement element, string Message)
        {
            if (string.IsNullOrWhiteSpace(Message)) return;
            element?.Click();
            // 注意：SendKeys可能不会在所有的UI自动化场景中都有效  
            // 它通常用于Windows Forms应用程序中的简单自动化任务  
            // 如果你的目标应用程序不是Windows Forms，或者它没有正确响应全局键盘事件，这可能不起作用  
            // 尝试全选并删除编辑框中的内容  
            SendKeys.SendWait("^a"); // Ctrl+A 全选  
            SendKeys.SendWait("{DELETE}"); // 删除键  
            SendKeys.SendWait(Message); // 删除键  

            // 注意：SendKeys发送的键盘事件是全局的，  
            // 所以如果当前焦点不在你想要的编辑框上，  
            // 这些按键可能会被发送到其他控件或应用程序。  
            // 确保在发送这些按键之前，编辑框具有焦点。  
        }
        /// <summary>
        /// 是否已经登录
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static bool IsLogin(this Window window)
        {
            window = new MainWindow().GetWindowById();
            var LoginTag = window.FindFirstDescendant(cf => cf.ByName("设置及其他"));
            return LoginTag != null;
        }
        /// <summary>
        /// 是否是公众号
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static bool IsGongZhongHao(this Window window)
        {
            return window.FindAllDescendants().Any(t => t.Name == "公众号主页");
        }
        /// <summary>
        /// 是否在聊天种有搜索网络结果
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void IsSearchWangGeJieGuo(this Window window, RobotModel Robot, RobotRobotOther RobotOther)
        {
            window = new MainWindow().GetWindowById();
            var IsWangGeJieGuo = window.FindAllDescendants().Any(t => t.Name == "搜索网络结果");
            if (IsWangGeJieGuo) window.SendRobotMessage(Robot, RobotOther);
        }
        /// <summary>
        /// 发送消息给自己
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void SendRobotMessage(this Window window, RobotModel Robot, RobotRobotOther RobotOther)
        {
            window.JoinCurrentRobot();
            window.SendMessage(Message: "搜索网络结果" + DateTime.Now, Robot: Robot, RobotOther: RobotOther, IsQun: false, RoomCount: 1, RoomName: Robot.RobotName, RoomAvatar: Robot.RobotAvatar);
        }
        /// <summary>
        /// 进入个人页面
        /// </summary>
        /// <param name="window"></param>
        public static void JoinCurrentRobot(this Window window)
        {
            var RobotBtn = window.FindFirstDescendant(cf => cf.ByName("导航"))?.FindAllChildren().FirstOrDefault();
            RobotBtn?.Click();
            Thread.Sleep(200);
            window.FindFirstDescendant()?.FindAllDescendants(t => t.ByControlType(controlType: ControlType.Button)).LastOrDefault()?.Click();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void Login(this Window window)
        {
            window = new MainWindow().GetWindowById();
            var IsLogin = window.IsLogin();
            if (IsLogin) return;
            new WinWechat().StartWechatProcessID();
            var ResetBtn = window.FindFirstDescendant(cf => cf.ByName("为了你的账号安全，请重新登录。").Or(cf.ByName("你已退出微信")));
            if (ResetBtn != null)
            {
                window.FindFirstDescendant(cf => cf.ByName("确定"))?.Click();
            }
            else
            {
                window = new MainWindow().GetWindowById();
            }
            var LoginBtn = window.FindFirstDescendant(cf => cf.ByName("进入微信").Or(cf.ByName("登录")));
            LoginBtn?.Click();
            Thread.Sleep(1000 * 10);
            window = new MainWindow().GetWindowById();
            var Code = window.FindFirstDescendant(cf => cf.ByName("扫码登录"));
            if (Code != null)
            {
                var ImgPath = window.Img();
                LoginManage.Login(ImgPath, LoginType.扫码.ToString(), "");
                Thread.Sleep(1000 * 60 * 5);
            }
            else
            {
                window = new MainWindow().GetWindowById();
                var MobileLogin = window.FindFirstDescendant(cf => cf.ByName("需在手机上完成登录"));
                if (MobileLogin != null)
                {
                    LoginManage.Login("", LoginType.确认.ToString(), "");
                    Thread.Sleep(1000 * 60 * 2);
                }
            }
        }
        /// <summary>
        /// 置顶
        /// </summary>
        /// <param name="window"></param>
        public static void Top(this Window window)
        {
            var Top = window.FindFirstDescendant(cf => cf.ByName("置顶"));
            if (Top != null) Top.Click();
        }
        /// <summary>
        /// 取消置顶
        /// </summary>
        /// <param name="window"></param>
        public static void CencelTop(this Window window)
        {
            var Top = window.FindFirstDescendant(cf => cf.ByName("取消置顶"));
            if (Top != null) Top.Click();
        }
        /// <summary>
        /// 机器人头像
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static RobotModel RobotInfo(this Window window, RobotRobotOther RobotOther = null)
        {
            var Robot = new AIJQR().GetRobotModel();
            if (Robot != null && !string.IsNullOrWhiteSpace(Robot.RobotCode) && Robot.ExpDate > DateTime.Now) return Robot;

            window = new MainWindow().GetWindowById();

            var RobotBtn = window.FindFirstDescendant(cf => cf.ByName("导航"))?.FindAllChildren().FirstOrDefault();
            if (RobotBtn == null) return new RobotModel { RobotAvatar = "", RobotCode = "", RobotName = "", };
            var NickName = RobotBtn?.Name;
            var winDescendant = window.FindFirstDescendant(cf => cf.ByLocalizedControlType("窗格"));
            if (winDescendant == null) return new RobotModel { RobotAvatar = "", RobotCode = "", RobotName = "", };
            var X = winDescendant.BoundingRectangle.X;
            var Y = winDescendant.BoundingRectangle.Y;
            // 获取头像图像
            var boundingRectangle = RobotBtn.BoundingRectangle;
            using var screenshot = window.Capture();
            boundingRectangle.X = boundingRectangle.X - X - 20;
            boundingRectangle.Y = boundingRectangle.Y - Y - 20;
            using var avatarImage = ImageService.CropImage(screenshot, boundingRectangle);
            var imgbase64 = ImageService.ImageBitmapToBase64(avatarImage);
            RobotBtn.Click();
            Thread.Sleep(1000);
            var RobotIntro = window.FindFirstDescendant()?.FindAllDescendants(t => t.ByControlType(controlType: ControlType.Text));
            var IsWechatNumber = false;
            var RobotNumber = string.Empty;
            foreach (var item in RobotIntro)
            {
                if (IsWechatNumber)
                {
                    RobotNumber = item.Name;
                    Console.WriteLine(item.Name);
                    break;
                }
                if (item.Name == "微信号：") { IsWechatNumber = true; }
                ;
            }
            window.FindFirstDescendant()?.FindAllDescendants(t => t.ByControlType(controlType: ControlType.Button)).LastOrDefault()?.Click();

            Robot = new RobotModel { RobotAvatar = imgbase64, RobotCode = RobotNumber, RobotName = NickName, ExpDate = DateTime.Now.AddDays(30) };
            if (!string.IsNullOrWhiteSpace(Robot.RobotCode))
            {
                new AIJQR().SetRobotModel(Robot);
            }
            window.SendMessage("启动微信" + DateTime.Now, Robot: Robot, RobotOther: RobotOther ?? new RobotRobotOther { }, IsQun: false, RoomCount: 1, RoomName: Robot.RobotName, RoomAvatar: Robot.RobotAvatar);
            return Robot;
            // 保存头像图像
            //avatarImage.Save($"Avatar.png", System.Drawing.Imaging.ImageFormat.Png);
        }
        /// <summary>
        /// 个人/群 头像
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static RoomModel RoomInfo(this Window window, string Name, AutomationElement automationElement, bool IsContact = false)
        {
            var Model = new AIJQR().GetRoomModel(Name);
            if (Model != null && !string.IsNullOrWhiteSpace(Model.Name) && Model.ExpDate > DateTime.Now && !IsContact) return Model;
            if (automationElement == null) return new RoomModel { Name = Name, Avatar = "" };
            var winDescendant = window.FindFirstDescendant(cf => cf.ByLocalizedControlType("窗格"));
            var X = winDescendant.BoundingRectangle.X;
            var Y = winDescendant.BoundingRectangle.Y;
            if (automationElement != null)
            {
                var NickName = automationElement.Name;
                // 获取头像图像
                var boundingRectangle = automationElement.BoundingRectangle;
                if (boundingRectangle.Width == 0 || boundingRectangle.Height == 0) return new RoomModel { Name = Name, Avatar = "" };
                using var screenshot = window.Capture();
                boundingRectangle.X = boundingRectangle.X - X - 6;
                boundingRectangle.Y = boundingRectangle.Y - Y - 6;

                using var avatarImage = IsContact ? ImageService.CropImageContact(screenshot, boundingRectangle) : ImageService.CropImage(screenshot, boundingRectangle);
                var imgbase64 = ImageService.ImageBitmapToBase64(avatarImage);
                Model = new RoomModel { Name = Name, Avatar = imgbase64, ExpDate = DateTime.Now.AddDays(70) };
                new AIJQR().SetRoomModel(Model);
                return Model;
                // 保存头像图像
                //avatarImage.Save($"AvatarHuiHua{item.Name}.png", System.Drawing.Imaging.ImageFormat.Png);
            }
            else
            {
                return new RoomModel { Name = Name, Avatar = "" };
            }
        }
        /// <summary>
        /// 群里人员的头像
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static UserModel SendAvatar(this Window window, string RoomName, string Name, AutomationElement automationElement)
        {
            var Model = new AIJQR().GetUserModel(RoomName, Name);
            if (Model != null && !string.IsNullOrWhiteSpace(Model.Name) && Model.ExpDate > DateTime.Now) return Model;

            if (automationElement == null) return new UserModel { Name = Name, Avatar = "" };
            var winDescendant = window.FindFirstDescendant(cf => cf.ByLocalizedControlType("窗格"));
            var X = winDescendant.BoundingRectangle.X;
            var Y = winDescendant.BoundingRectangle.Y;
            if (automationElement != null)
            {
                var boundingRectangle = automationElement.BoundingRectangle;
                if (boundingRectangle.Width == 0 || boundingRectangle.Height == 0) return new UserModel { Name = Name, Avatar = "" };
                using var screenshot = window.Capture();
                boundingRectangle.X = boundingRectangle.X - X - 20;
                boundingRectangle.Y = boundingRectangle.Y - Y - 20;
                using var avatarImage = ImageService.CropImageHuiHua(screenshot, boundingRectangle);
                var imgbase64 = ImageService.ImageBitmapToBase64(avatarImage);
                Model = new UserModel { Name = Name, RoomName = RoomName, Avatar = imgbase64, ExpDate = DateTime.Now.AddDays(7) };
                new AIJQR().SetUserModel(Model);
                return Model;
            }
            else
            {
                return new UserModel { Name = Name, Avatar = "" };
            }
        }
        private static List<string> ImgKeyList = new List<string> { };
        /// <summary>
        /// 发送的图片
        /// </summary>
        /// <param name="window"></param>
        /// <param name="automationElement"></param>
        /// <param name="IsRobotSend"></param>
        /// <param name="IsQun"></param>
        /// <param name="Key"></param>
        /// <param name="SendMessage"></param>
        /// <param name="ImgUrl"></param>
        public static void Img(this Window window, AutomationElement automationElement, bool IsRobotSend, bool IsQun, string Key, ref string SendMessage, ref string ImgUrl)
        {
            if (ImgKeyList.Contains(Key)) return;
            ImgKeyList.Add(Key);
            var boundingRectangle = automationElement.BoundingRectangle;
            window.CencelTop();
            if (IsRobotSend)
            {
                MainWindowType.SetCursorPos(boundingRectangle.X - 20, boundingRectangle.Y);
            }
            else
            {
                MainWindowType.SetCursorPos(boundingRectangle.X + 56, (boundingRectangle.Y + (IsQun ? 30 : 20)));
            }
            // 模拟鼠标左键按下
            MainWindowType.LEFT();
            //MsgRight.Click();
            Thread.Sleep(2000);
            window = new MainWindow().GetWindowById();
            var ImgShow = window.FindFirstDescendant(t => t.ByName("上一张").Or(t.ByName("下一张")).Or(t.ByName("已是第一张")).Or(t.ByName("已是最后一张")));
            if (ImgShow != null)
            {
                var ImgTiQuBtn = window.FindFirstDescendant(t => t.ByName("提取文字"));
                ImgTiQuBtn?.Click();
                Thread.Sleep(2000);
                var TempSendMessage = window.FindAllDescendants(t => t.ByControlType(ControlType.Text)).LastOrDefault(t => !string.IsNullOrEmpty(t.Name))?.Name;
                if (!string.IsNullOrWhiteSpace(TempSendMessage))
                {
                    SendMessage = TempSendMessage;
                    Key = new SignService().SignMD5(SendMessage);
                }
                if (!ImgKeyList.Contains(Key))
                {
                    ImgTiQuBtn?.Click();
                    ImgUrl = window.Img();
                }
                window.FindFirstDescendant(t => t.ByName("关闭"))?.Click();
            }
            window = new MainWindow().GetWindowById();
            window.Top();
        }
        /// <summary>
        /// 发送的图片
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static string Img(this Window window)
        {
            var winDescendant = window.FindFirstDescendant(cf => cf.ByLocalizedControlType("窗格"));
            var X = winDescendant.BoundingRectangle.X;
            var Y = winDescendant.BoundingRectangle.Y;
            var boundingRectangle = winDescendant.BoundingRectangle;
            if (boundingRectangle.Width == 0 || boundingRectangle.Height == 0) return "";
            using var screenshot = window.Capture();
            boundingRectangle.X = boundingRectangle.X - X;
            boundingRectangle.Y = boundingRectangle.Y - Y;
            using var avatarImage = ImageService.Img(screenshot, boundingRectangle);
            //var imgbase64 = ImageService.ImageBitmapToBase64(avatarImage);
            var ImgPath = $"Data/Img/{DateTime.Now.ToString("yyyyMMddHHmmss")}.png";
            var FilePath = Path.GetFullPath(ImgPath);
            string directoryName = Path.GetDirectoryName(FilePath);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            avatarImage.Save(FilePath, System.Drawing.Imaging.ImageFormat.Png);
            var result = FileService.Upload(FilePath);
            if (File.Exists(FilePath))
            {
                File.Delete(FilePath);
            }
            return result.Url;

        }
        /// <summary>
        /// 发送的附件
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static void SendFile(this Window window, string Url, string FileName, string MessageType, RobotModel Robot, RobotRobotOther RobotOther, bool IsQun, int RoomCount, string RoomName, string RoomAvatar, string HistoryId = "", bool IsForward = false)
        {

            MessageManage.Send(Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, Message: FileName, RoomName: RoomName, RoomAvatar: RoomAvatar, ImgUrl: Url, MessagesType: MessageType, HistoryId: HistoryId, IsForward: IsForward);
            var ImgPath = $"{AppDomain.CurrentDomain.BaseDirectory}Data\\Img\\{FileName}";
            if (MessageType != MessagesType.可下载图片的链接.ToString())
            {
                FileService.Down(Url, ImgPath);
            }
            else
            {
                var Model = new OtherConfig().GetConfigModel();
                ImgPath = ImageService.UrlToImg(Url, "", Model.QuerySelector, Model.ExecutablePath);
            }

            if (File.Exists(ImgPath))
            {
                var SendFile = window.FindFirstDescendant(t => t.ByName("发送文件"));
                SendFile.Click();
                window = new MainWindow().GetWindowById();
                var Cencel = window.FindAllDescendants().FirstOrDefault(t => t.Parent != null && (t.Parent.ControlType == ControlType.Window) && t.Parent.Name == "打开" && t.Name == "取消" && t.ControlType == ControlType.Button);
                var ImgPathInput = window.FindAllDescendants().FirstOrDefault(t => t.Parent != null && (t.Parent.ControlType == ControlType.ComboBox) && t.Parent.Name == "文件名（N）" && t.Name == "文件名（N）" && t.ControlType == ControlType.Edit);
                WechatAuto.ClearEditTextBoxUsingKeyboard(ImgPathInput, ImgPath);
                var Open = window.FindAllDescendants().FirstOrDefault(t => t.Parent != null && (t.Parent.ControlType == ControlType.Window) && t.Parent.Name == "打开" && t.Name == "打开(O)" && t.ControlType == ControlType.SplitButton);
                Open?.Click();
                AutomationElement Send = null;
                //var Cencel1 = window.FindAllDescendants().FirstOrDefault(t => t.Parent != null && t.Parent.ControlType == ControlType.Pane && t.Name == "取消" && t.ControlType == ControlType.Button);
                window = new MainWindow().GetWindowById();
                foreach (var item in window.FindAllDescendants().Where(t => t.Parent != null && t.Parent.ControlType == ControlType.Pane && t.ControlType == ControlType.Button))
                {
                    if (item.Name == "发送（1）")
                    {
                        Send = item;
                        continue;
                    }
                }
                Send?.Click();
                var Cencel1 = window.FindAllDescendants().FirstOrDefault(t => t.Parent != null && t.Parent.ControlType == ControlType.Pane && t.Name == "取消" && t.ControlType == ControlType.Button);
                if (Cencel1 != null && Cencel1.BoundingRectangle.X > 0)
                {
                    Cencel1?.Click();
                }
                if (Send == null)
                {
                    if (Cencel != null && Cencel.BoundingRectangle.X > 0)
                    {
                        Cencel?.Click();
                    }
                }
                File.Delete(ImgPath);
            }

        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Message"></param>
        public static void SendMessage(this Window window, string Message, RobotModel Robot, RobotRobotOther RobotOther, bool IsQun, int RoomCount, string RoomName, string RoomAvatar, string HistoryId = "", bool IsForward = false)
        {
            SendMessage(window, Message: Message, Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar, MessageType: MessagesType.文本.ToString(), HistoryId: HistoryId, IsForward: IsForward);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Message"></param>
        /// <param name="MessageType"></param>
        public static void SendMessage(this Window window, string Message, RobotModel Robot, RobotRobotOther RobotOther, bool IsQun, int RoomCount, string RoomName, string RoomAvatar, string MessageType, string HistoryId = "", bool IsForward = false)
        {
            SendMessage(window, Message: Message, MessageType: MessageType, List: new List<RoomTaskFile> { }, Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar, HistoryId: HistoryId, IsForward: IsForward);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void SendMessage(this Window window, string Message, RobotModel Robot, RobotRobotOther RobotOther, bool IsQun, int RoomCount, string RoomName, string RoomAvatar, string MessageType, List<RoomTaskFile> List, string HistoryId = "", bool IsForward = false)
        {
            if (List != null && List.Any())
            {
                foreach (var item in List)
                {
                    window.SendFile(Url: item.Url, FileName: item.Name, MessageType: MessageType, Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar);
                }
            }
            if (string.IsNullOrWhiteSpace(Message))
            {
                return;
            }
            Message = Message.Trim();
          


            var MsgSend = window.FindFirstDescendant(cf => cf.ByName("输入")).AsTextBox();
            
            MsgSend?.Click();
            Thread.Sleep(500);
            var MsgSendButton = window.FindFirstDescendant(cf => cf.ByName("发送(S)"));
            if (MsgSendButton != null)
            {
                if (MessageType == MessagesType.图片.ToString() || MessageType == MessagesType.按钮.ToString())
                {
                    var boundingRectangle = MsgSendButton.BoundingRectangle;
                    MainWindowType.SetCursorPos(boundingRectangle.X - 20, boundingRectangle.Y - 20);
                    MainWindowType.LEFT();
                    Thread.Sleep(200);
                    SetText(Message, false);
                }
                else
                {
                    var boundingRectangle = MsgSendButton.BoundingRectangle;
                    MainWindowType.SetCursorPos(boundingRectangle.X - 20, boundingRectangle.Y - 20);
                    MainWindowType.LEFT();
                    Thread.Sleep(200);
                    SetText(Message, true);
                }
                MsgSendButton.DrawHighlight(System.Drawing.Color.Red);
                Thread.Sleep(200);
                MsgSendButton?.Click();
                MessageManage.Send(Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, Message: Message, RoomName: RoomName, RoomAvatar: RoomAvatar, ImgUrl: "", MessagesType: MessagesType.文本.ToString(), HistoryId: HistoryId, IsForward: IsForward);
            }

        }
        /// <summary>
        /// 发送文本
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="ReceiverName"></param>
        /// <param name="List"></param>
        /// <param name="MsgType"></param>
        public static void ForwardMessage(this Window window, RobotModel Robot, RobotRobotOther RobotOther, string ReceiverName, string Message, string HistoryId, bool IsForward = false)
        {
            window.ForwardMessage(Robot, RobotOther, ReceiverName, Message, MessagesType.文本.ToString(), List: new List<RoomTaskFile> { }, HistoryId: HistoryId, IsForward: IsForward);
        }
        /// <summary>
        /// 处理附件
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="ReceiverName"></param>
        /// <param name="List"></param>
        /// <param name="MsgType"></param>
        public static void ForwardMessage(this Window window, RobotModel Robot, RobotRobotOther RobotOther, string ReceiverName, string Message, string MessageType, List<RoomTaskFile> List, string HistoryId, bool IsForward = false)
        {
            if (string.IsNullOrWhiteSpace(ReceiverName)) return;
            var FindAllDescendants = window.FindAllDescendants();
            FindAllDescendants.Where(s => s.Name == "聊天").FirstOrDefault().Click(false);
            var search = FindAllDescendants.FirstOrDefault(s => s.Name == "搜索");
            search.FocusNative();
            search.Focus();
            search.Click();
            var SearchParent = search.Parent;
            if (SearchParent != null)
            {
                var Search = SearchParent.FindAllChildren().FirstOrDefault(s => s.ControlType == ControlType.Text).AsTextBox();
                Search.Text = ReceiverName;
                Thread.Sleep(3000);
                var itemReceiverName = window.FindAllDescendants().Where(s => s.ControlType == ControlType.ListItem && !string.IsNullOrEmpty(s.Name) && s.Name == ReceiverName).ToList();
                AutomationElement ReceiverNameElement = null;
                if (itemReceiverName.Count() > 1)
                {
                    ReceiverNameElement = itemReceiverName.FirstOrDefault(s => s.Parent != null && s.Parent.Name.Contains("@str:IDS_FAV_SEARCH_RESULT"));
                }
                if (ReceiverNameElement == null)
                {
                    ReceiverNameElement = itemReceiverName.FirstOrDefault();
                }
                if (ReceiverNameElement != null)
                {
                    //搜索不到
                    if (ReceiverNameElement.BoundingRectangle.Height != 31)
                    {
                        ReceiverNameElement.Click();
                    }
                    if (!string.IsNullOrWhiteSpace(Message))
                    {
                        window.SendMessage(Message: Message, Robot: Robot, RobotOther: RobotOther, IsQun: false, RoomCount: -1, RoomName: ReceiverName, RoomAvatar: "",
                             HistoryId: HistoryId,
                            IsForward: IsForward);
                    }

                    if (List != null && List.Any())
                    {
                        foreach (var item in List)
                        {
                            window.SendFile(Url: item.Url, FileName: item.Name, MessageType: MessageType, Robot: Robot, RobotOther: RobotOther, IsQun: false, RoomCount: -1, RoomName: ReceiverName, RoomAvatar: "", IsForward: IsForward);
                        }
                    }

                }
            }
        }
        /// <summary>
        /// 转发
        /// </summary>
        /// <param name="window"></param>
        /// <param name="ReceiverName">转发接受者</param>
        /// <param name="RobotName">机器人</param>
        /// <param name="RoomName">房间-群/个人</param>
        /// <param name="NickName">（需要转发的）消息发送者</param>
        /// <param name="Message"></param>
        public static void ForwardMessage(this Window window, RobotModel Robot, RobotRobotOther RobotOther, string ReceiverName, string RoomName, string NickName, string Message)
        {
            if (RoomName == NickName) NickName = "";
            Message = $"转发来自【{RoomName} {NickName}】的消息: \n\n{Message}";
            ForwardMessage(window, Robot, RobotOther, ReceiverName, Message, "");
        }
        /// <summary>
        /// 邀请
        /// </summary>
        /// <param name="window"></param>
        /// <param name="SendMessage"></param>
        /// <param name="RobotName"></param>
        /// <param name="Message"></param>
        /// <param name="RoomName"></param>
        /// <returns></returns>
        public static bool ShareMessage(this Window window, RobotModel Robot, RobotRobotOther RobotOther, string SendMessage, string Message, string RoomName, int RoomCount, string RoomAvatar)
        {
            if ((SendMessage.Contains("加入了群聊") && SendMessage.Contains("邀请")) || (SendMessage.Contains("加入群聊") && SendMessage.Contains("通过扫描")))
            {
                var ShareType = string.Empty;
                var YaoQingRenNickName = string.Empty;
                var JinQunRenNickName = string.Empty;
                if (SendMessage.Contains("邀请")) ShareType = "邀请";
                else if (SendMessage.Contains("通过扫描")) ShareType = "二维码";
                if (ShareType == "邀请")
                {
                    JinQunRenNickName = SendMessage.Split("邀请")[1].Trim().Replace("加入了群聊", "").Replace("\"", "");
                    YaoQingRenNickName = SendMessage.Split("邀请")[0].Trim();
                    if (YaoQingRenNickName == "你") YaoQingRenNickName = Robot.RobotName;
                    if (!string.IsNullOrWhiteSpace(Message)) window.SendMessage($"@{JinQunRenNickName} \n {Message}", Robot: Robot, RobotOther: RobotOther, IsQun: true, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar);
                }
                else if (ShareType == "二维码")
                {
                    JinQunRenNickName = SendMessage.Split("通过扫描")[0].Trim().Replace("\"", "");
                    YaoQingRenNickName = SendMessage.Split("通过扫描")[1].Replace("分享的二维码加入群聊", "").Trim();
                    if (YaoQingRenNickName == "你") YaoQingRenNickName = Robot.RobotName;
                    if (!string.IsNullOrWhiteSpace(Message)) window.SendMessage($"@{JinQunRenNickName} \n {Message}", Robot: Robot, RobotOther: RobotOther, IsQun: true, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar);
                }
                YaoQingRenNickName = YaoQingRenNickName.Replace("\"", "");
                ShareManage.Send(Robot, RobotOther, RoomName, JinQunRenNickName, YaoQingRenNickName, Message, "", ShareType);
                return true;
            }
            return false;
        }
        /// <summary>
        /// 加好友
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="SendMessage"></param>
        /// <param name="Message"></param>
        /// <param name="RoomName"></param>
        /// <returns></returns>
        public static bool AddFriend(this Window window, RobotModel Robot, RobotRobotOther RobotOther, string SendMessage, RoomConfig Config, string RoomName, string RoomAvatar)
        {
            var WelcomeMessage = Config.Model.FriendWelcomeMessage;
            var ActivityId = "";
            if (Config.Activity != null)
            {
                WelcomeMessage = Config.Activity.ActivityWelcomeMessage;
                ActivityId = Config.Activity.ActivityId;
            }
            bool IsBeiDongFriend = false;

            {
                var Friend = window.FindFirstDescendant(t => t.ByControlType(ControlType.Button).And(t.ByName("添加")));
                if (Friend != null)
                {
                    IsBeiDongFriend = true;
                    //Friend.DrawHighlight(System.Drawing.Color.Red);
                    Friend.Click();
                    Thread.Sleep(1000 * 2);
                }
            }
            if (SendMessage == "以上是打招呼的内容" && !IsBeiDongFriend)
            {
                new LoggerService().RequestMsgDebug(nameof(AddFriend), RoomName, IsBeiDongFriend.ToString());
                window = new MainWindow().GetWindowById();
                var Friend = window.FindFirstDescendant(t => t.ByControlType(ControlType.Button).And(t.ByName("添加")));
                if (Friend != null)
                {
                    IsBeiDongFriend = true;
                    //Friend.DrawHighlight(System.Drawing.Color.Red);
                    Friend.Click();
                    Thread.Sleep(1000 * 2);
                }
            }

            if (IsBeiDongFriend || ((SendMessage.StartsWith("你已添加了") && SendMessage.EndsWith("，现在可以开始聊天了。")) || SendMessage == "我通过了你的朋友验证请求，现在我们可以开始聊天了"))
            {

                if (!string.IsNullOrWhiteSpace(Config.Model.FWXZ)) window.SendMessage(Message: $"{Config.Model.FWXZ}", Robot: Robot, RobotOther: RobotOther, IsQun: false, RoomCount: 1, RoomName: RoomName, RoomAvatar: RoomAvatar, MessageType: MessagesType.按钮.ToString());

                if (!string.IsNullOrWhiteSpace(WelcomeMessage)) window.SendMessage(Message: $"{WelcomeMessage}", Robot: Robot, RobotOther: RobotOther, IsQun: false, RoomCount: 1, RoomName: RoomName, RoomAvatar: RoomAvatar, MessageType: MessagesType.按钮.ToString());

                ShareManage.Send(Robot, RobotOther, RoomName, RoomName, Robot.RobotName, WelcomeMessage, ActivityId, "好友");
                return true;
            }
            return false;
        }
        /// <summary>
        /// 点击主页面的聊天 是否有气泡
        /// </summary>
        /// <param name="window"></param>
        public static bool IsBubble(this Window window)
        {
            var element = window.FindAllDescendants().Where(s => s.Parent != null && s.Parent.Name == "导航" && s.Name == "聊天").FirstOrDefault();
            if (element == null) return false;
            var IsMessage = false;
            if (element.GetSupportedPatterns().Count() > 0)
            {
                if (element.Patterns.Value.IsSupported)
                {
                    var valuePattern = element.Patterns.Value.Pattern;
                    string value = valuePattern.Value;
                    IsMessage = value.Contains("条新消息");
                    // 输出值
                    Console.WriteLine(value);
                }
            }
            if (IsMessage)
            {
                element?.DoubleClick();
                Thread.Sleep(200);
            }
            return IsMessage;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static int GetMillisecondsTimeout(RobotRobotOther RobotOther)
        {
            var Hour = DateTime.Now.Hour;
            var Second = WaitSecondManage.GetWaitSecondList(RobotOther.Id).FirstOrDefault(t => t.EndHour > Hour && t.StartHour <= Hour);
            if (Second == null) Second = new WaitSecondModel { MinSecond = 30, MaxSecond = 60, };
            int Result = new Random().Next(Second.MinSecond * 1000, Second.MaxSecond * 1000);
            return Result;
        }
        /// <summary>
        /// 转人工或者AI 是否为真实人工
        /// </summary>
        /// <param name="window"></param>
        public static bool IsRealUser(this Window window, RobotModel Robot, RobotRobotOther RobotOther)
        {
            var Result = false;
            var MsgRight = window.FindAllDescendants().FirstOrDefault(t => t.Name == "消息" && t.ControlType == ControlType.List);
            if (MsgRight == null) return Result;
            var MsgRightList = MsgRight.FindAllDescendants(t => t.ByControlType(ControlType.ListItem));
            if (MsgRightList == null || MsgRightList.Count() == 0) return Result;
            var SendMessage = string.Empty;//发送的消息
            var itemMsgInfo = MsgRightList.LastOrDefault();
            SendMessage = itemMsgInfo.Name;//发送的消息

            if (SendMessage == "转员工" || SendMessage.Contains("客服已停止"))
            {
                if (!SendMessage.Contains("客服已停止")) window.SendMessage(Message: $"客服已停止 {DateTime.Now.ToString("g")}", Robot: Robot, RobotOther: RobotOther, IsQun: false, RoomCount: 1, RoomName: Robot.RobotName, RoomAvatar: Robot.RobotAvatar);
                Result = true;
            }
            if ((SendMessage.ToUpper() == "转小雁") && !SendMessage.Contains("客服已启用"))
            {
                if (!SendMessage.Contains("客服已启用")) window.SendMessage(Message: $"客服已启用 {DateTime.Now.ToString("g")}", Robot: Robot, RobotOther: RobotOther, IsQun: false, RoomCount: 1, RoomName: Robot.RobotName, RoomAvatar: Robot.RobotAvatar);
            }
            return Result;
        }
        private static bool IsReLoginWork = false;
        /// <summary>
        /// 是否在工作
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="RestingStartTime"></param>
        /// <param name="RestingEndTime"></param>
        /// <returns></returns>
        public static bool IsWork(Window window, RobotModel Robot, string RestingStartTime, string RestingEndTime, bool ResetWechat)
        {
            if (!string.IsNullOrWhiteSpace(RestingStartTime) && !string.IsNullOrWhiteSpace(RestingEndTime))
            {
                DateTime RestringStartDate = default;
                DateTime RestringEndDate = default;
                var CurrentDay = Convert.ToDateTime(DateTime.Now.ToString("D"));
                var RestringStartInt = Convert.ToInt32(RestingStartTime.Replace(":", ""));
                var RestringEndInt = Convert.ToInt32(RestingEndTime.Replace(":", ""));
                RestringStartDate = Convert.ToDateTime($"{CurrentDay.ToString("D")} {RestingStartTime}");
                RestringEndDate = Convert.ToDateTime($"{CurrentDay.AddDays(RestringStartInt > RestringEndInt ? 1 : 0).ToString("D")} {RestingEndTime}");
                if (RestringStartDate < DateTime.Now && DateTime.Now < RestringEndDate)
                {
                    var SleepSeconds = (RestringEndDate - DateTime.Now).TotalSeconds;
                    IsReLoginWork = !IsReLoginWork;
                    if (IsReLoginWork)
                    {
                        if (ResetWechat)
                        {
                            window = new MainWindow().GetWindowById(true);
                        }
                        return false;
                    }
                    else
                    {
                        Console.WriteLine($"{DateTime.Now} {Robot.RobotName}:{Robot.RobotCode}:休息中,{RestringEndDate}开始工作");
                        Thread.Sleep(Convert.ToInt32(SleepSeconds * 1000));
                    }
                }
                return true;
            }
            return true;

        }
        /// <summary>
        /// 返回false 则不需要记录 昨天的数据或者是 条件没有大于=3条
        /// </summary>
        /// <param name="window"></param>
        /// <param name="automationElement"></param>
        /// <param name="MsgDateTime"></param>
        /// <returns></returns>
        public static bool FindPathText(this Window window, AutomationElement automationElement, out DateTime MsgDateTime)
        {
            MsgDateTime = default;
            var AllText = automationElement.FindAllByXPath("//*/Text");
            if ((AllText == null || AllText.Length < 3)) return false;
            var MsgDate = AllText[1].Name;//时间
            if (!MsgDate.Contains(":")) return false;//只处理今天的数据

            MsgDateTime = Convert.ToDateTime(DateTime.Now.ToString($"yyyy-MM-dd {MsgDate}:00"));
            return true;
        }
        /// <summary>
        /// 获取会话信息
        /// </summary>
        /// <param name="window"></param>
        /// <param name="automationElement"></param>
        /// <param name="IsQun"></param>
        /// <param name="RoomCount"></param>
        /// <param name="RoomName"></param>
        /// <param name="RoomNameOrg"></param>
        public static void FindRoomInfo(this Window window, AutomationElement automationElement, out bool IsQun, out int RoomCount, out string RoomName, out string RoomNameOrg)
        {
            IsQun = true;
            RoomCount = 1;
            RoomName = automationElement.Name;//群/个人名称
            RoomNameOrg = RoomName;//群原来的名称/个人名称
            var WechatMsgRightTop = window.FindAllDescendants().FirstOrDefault(t => t.Name == "聊天信息")?.Parent?.Parent?.Parent?.FindAllDescendants(t => t.ByControlType(ControlType.Text));
            if (WechatMsgRightTop?.Count() > 0)
            {
                if (WechatMsgRightTop.Count() <= 2)
                {
                    var RightRoomName = WechatMsgRightTop.FirstOrDefault();
                    var RightRoomCount = WechatMsgRightTop.LastOrDefault();
                    //个人
                    if (RightRoomName == RightRoomCount)
                    {
                        IsQun = false;
                        RoomName = RightRoomName.Name;
                    }
                    //群未修改名称
                    else
                    {
                        RoomName = RightRoomName.Name.Replace(RightRoomCount.Name, "");
                        RoomCount = Convert.ToInt32(RightRoomCount.Name.Replace("(", "").Replace(")", ""));
                    }
                    RoomNameOrg = RoomName;
                }
                else if (WechatMsgRightTop.Count() == 3)//群的别名
                {
                    var RightRoomName = WechatMsgRightTop[0];
                    var RightRoomCount = WechatMsgRightTop[1];
                    RoomNameOrg = WechatMsgRightTop[2].Name;
                    RoomName = RightRoomName.Name.Replace(RightRoomCount.Name, "");
                    RoomCount = Convert.ToInt32(RightRoomCount.Name.Replace("(", "").Replace(")", ""));
                }
            }
        }
        /// <summary>
        /// 反馈false 不合法需要 continue 退出 处理特殊消息 语音 图片
        /// </summary>
        /// <param name="window"></param>
        /// <param name="automationElement"></param>
        /// <param name="automationElementSendMsg"></param>
        /// <param name="SendData"></param>
        /// <param name="IsRobotSend"></param>
        /// <param name="IsQun"></param>
        /// <param name="SendMessage"></param>
        /// <param name="MessageType"></param>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        public static bool OptOtherMsg(this Window window, AutomationElement automationElement, AutomationElement automationElementSendMsg, RobotRobotOther RobotOther, SENDDATA SendData, bool IsRobotSend, bool IsQun, ref string SendMessage, ref string MessageType, ref string ImgUrl)
        {

            SendData.RequestId = new SignService().SignMD5(SendData);
            if (RobotOther.IsReceiveVoice && SendMessage.Contains("[语音]") && !SendMessage.Contains("\n引用"))
            {
                var TempSendMessage = automationElement.FindAllDescendants(t => t.ByControlType(ControlType.Text)).LastOrDefault(t => t.Parent?.ControlType == ControlType.Pane)?.Name;
                if (!string.IsNullOrWhiteSpace(TempSendMessage))
                {
                    SendMessage = TempSendMessage;
                    MessageType = MessagesType.语音.ToString();
                }
                if (string.IsNullOrWhiteSpace(SendMessage))
                {
                    return false;
                }
            }
            else if (RobotOther.IsReceivePic && SendMessage.Contains("[图片]") && !SendMessage.Contains("\n引用"))
            {
                MessageType = MessagesType.图片.ToString();
                window.Img(automationElementSendMsg, IsRobotSend, IsQun, SendData.RequestId, ref SendMessage, ref ImgUrl);
                if (string.IsNullOrWhiteSpace(ImgUrl))
                {
                    return false;
                }
            }

            return true;
        }
        /// <summary>
        /// 无应答
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="Config"></param>
        /// <param name="RoomName"></param>
        /// <param name="IsQun"></param>
        /// <param name="RoomSendNickName"></param>
        /// <param name="SendMessage"></param>
        public static void WuYingDa(this Window window, RobotModel Robot, RobotRobotOther RobotOther, RoomConfig Config, bool IsQun, string RoomName, string RoomAvatar, int RoomCount, string RoomSendNickName, string SendMessage, string MessageType)
        {

            if (Config.Model.NoResponselnt == (int)NoResponseType.ResponseType1 || Config.Model.NoResponselnt == (int)NoResponseType.ResponseType0)
            {
                var KeyValue = Config.List.Where(t => t.Type == KeyType.无应答.ToString()).ToList();
                if (new AIJQRManGroup().OptRes(KeyValue, SendMessage)) Config.Model.NoResponseMessage = KeyValue.FirstOrDefault(t => SendMessage.Contains(t.Key, System.StringComparison.OrdinalIgnoreCase)).Value;
                var QunTop = IsQun ? $"@{RoomSendNickName}  \n" : "";
                window.SendMessage($" {QunTop} {Config.Model.NoResponseMessage}", Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar, MessageType: MessageType);

            }
            if (Config.Model.NoResponselnt == (int)NoResponseType.ResponseType2 || Config.Model.NoResponselnt == (int)NoResponseType.ResponseType0)
            {
                var GroupReceiverName = new AIJQRManGroup().GetReceiverRoomName(Config.Model.ZFJSZ, RoomName);
                window.ForwardMessage(Robot, RobotOther, GroupReceiverName, RoomName, RoomSendNickName, SendMessage);
            }
        }
        /// <summary>
        /// 处理AI越界越界时
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="Config"></param>
        /// <param name="IsQun"></param>
        /// <param name="RoomSendNickName"></param>
        /// <param name="Message"></param>
        public static void YueJie(this Window window, RobotModel Robot, RobotRobotOther RobotOther, RoomConfig Config, bool IsQun, string RoomName, string RoomAvatar, int RoomCount, string RoomSendNickName, string Message, string MessageType)
        {
            var KeyValue = Config.List.Where(t => t.Type == KeyType.越界.ToString()).ToList();
            //处理越界关键词
            Message = new AIJQRManGroup().OptSensitive(KeyValue, Message);
            var QunTop = IsQun ? $"@{RoomSendNickName}  \n" : "";
            if (RobotOther.IsAutoFenDuan) Message = OptMessage(Message);

            window.SendMessage(Message: $" {QunTop} {Message}", Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar, MessageType: MessageType);

        }
        /// <summary>
        /// 费用
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="Config"></param>
        /// <param name="IsQun"></param>
        /// <param name="RoomSendNickName"></param>
        /// <param name="Message"></param>
        public static bool FeiYong(this Window window, RobotModel Robot, RobotRobotOther RobotOther, RoomConfig Config, bool IsQun, string RoomName, string RoomAvatar, int RoomCount, string NickName, string Message)
        {

            var KeyValue = Config.List.Where(t => t.Type == KeyType.费用.ToString()).ToList();
            if (KeyValue.Any())
            {
                if (new AIJQRManGroup().OptRes(KeyValue, Message))
                {
                    var result = PriceManage.GetPriceList(Robot, Config.Model.Id, IsQun, RoomName, NickName, Message);
                    //有查询到业务费用
                    if (result.ActionOK)
                    {
                        var SendMessage = string.Empty;
                        var PriceType = result.Data.GroupBy(t => t.PriceType);
                        //查询费用
                        foreach (var item in PriceType)
                        {
                            //物业费
                            //1-1  url
                            //1-2  url
                            if (!string.IsNullOrWhiteSpace(item.Key)) SendMessage += $"{item.Key}:\n ";
                            foreach (var itemurl in item.ToList())
                            {
                                SendMessage += $"{itemurl.PriceDec}  {(itemurl.Url)} ";
                            }
                            var QunTop = IsQun ? $"@{NickName}  \n" : "";
                            window.SendMessage(Message: $" {QunTop}{SendMessage}", Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, RoomName: RoomName, RoomAvatar: RoomAvatar);
                        }
                    }
                    return result.ActionOK;
                }
            }
            return false;
        }
        /// <summary>
        /// 敏感词
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="Config"></param>
        /// <param name="IsQun"></param>
        /// <param name="RoomName"></param>
        /// <param name="NickName"></param>
        /// <param name="Message"></param>
        /// <returns>true 时跳出</returns>
        public static bool MinGanCi(this Window window, RobotModel Robot, RobotRobotOther RobotOther, RoomConfig Config, bool IsQun, string RoomName, string RoomAvatar, int RoomCount, string NickName, string Message)
        {
            var KeyValue = Config.List.Where(t => t.Type == KeyType.敏感词.ToString()).ToList();
            //存在敏感词时直接反馈
            if (new AIJQRManGroup().OptRes(KeyValue, Message))
            {
                var QunTop = IsQun ? $"@{NickName}  \n" : "";

                window.SendMessage(Message: $" {QunTop}{KeyValue.FirstOrDefault(t => Message.Contains(t.Key, System.StringComparison.OrdinalIgnoreCase)).Value}", Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, MessageType: MessagesType.文本.ToString(), List: new List<RoomTaskFile> { }, RoomName: RoomName, RoomAvatar: RoomAvatar);

                var RoomReceiverName = new AIJQRManGroup().GetReceiverRoomName(Config.Model.ZFJSZ, RoomName);
                window.ForwardMessage(Robot, RobotOther, RoomReceiverName, RoomName, NickName, Message);
                return true;
            }
            return false;

        }
        /// <summary>
        /// 客服
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="Config"></param>
        /// <param name="IsQun"></param>
        /// <param name="NickName"></param>
        /// <param name="Message"></param>
        /// <returns>true 时跳出</returns>
        public static bool KeFu(this Window window, RobotModel Robot, RobotRobotOther RobotOther, RoomConfig Config, bool IsQun, string RoomName, string RoomAvatar, int RoomCount, string NickName, string Message)
        {

            var KeyValue = Config.List.Where(t => t.Type == KeyType.客服.ToString()).ToList();
            //存在客服直接反馈
            if (new AIJQRManGroup().OptRes(KeyValue, Message))
            {
                var QunTop = IsQun ? $"@{NickName}  \n" : "";
                var KeyConfig = KeyValue.FirstOrDefault(t => Message.Contains(t.Key, System.StringComparison.OrdinalIgnoreCase));
                if (KeyConfig.MessageTypeFile)
                {
                    var Files = new List<RoomTaskFile> { new RoomTaskFile { Name = KeyConfig.FileName, Url = KeyConfig.Url } };
                    window.SendMessage(Message: $" {QunTop}{KeyConfig.Value}", Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, MessageType: MessagesType.文本.ToString(), List: Files, RoomName: RoomName, RoomAvatar: RoomAvatar);
                }
                else
                {
                    window.SendMessage(Message: $" {QunTop}{KeyConfig.Value}", Robot: Robot, RobotOther: RobotOther, IsQun: IsQun, RoomCount: RoomCount, MessageType: MessagesType.文本.ToString(), List: new List<RoomTaskFile> { }, RoomName: RoomName, RoomAvatar: RoomAvatar);
                }
                return true;
            }
            return false;
        }
        private static List<(string, DateTime)> sendTaskIdList = new List<(string, DateTime)> { };
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void Task(this Window window, RobotModel Robot, RobotRobotOther RobotOther)
        {
            var taskList = TaskManage.GetTaskList(Robot, RobotOther);
            foreach (var item in taskList)
            {
                var TotalSeconds = (DateTime.Now - item.SendDate).TotalSeconds;
                if (TotalSeconds > 0 && TotalSeconds < 60 * 60 * 12 && !sendTaskIdList.Any(t => t.Item1 == item.TaskId))
                {
                    if (item.MessageTypeFile)
                    {
                        window.ForwardMessage(Robot: Robot, RobotOther: RobotOther, ReceiverName: item.RoomName, Message: item.Message, MessageType: item.MessageType, List: item.List, HistoryId: item.HistoryId, IsForward: true);
                    }
                    else
                    {
                        window.ForwardMessage(Robot: Robot, RobotOther: RobotOther, ReceiverName: item.RoomName, Message: item.Message, HistoryId: item.HistoryId, IsForward: true);
                    }
                    sendTaskIdList.Add((item.TaskId, DateTime.Now));
                    TaskManage.SendTask(Robot, RobotOther, item.TaskId);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private static List<ContactTaskMap> contactTasks = new List<ContactTaskMap> { };
        /// <summary>
        /// 添加通讯录
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void AddContacts(this Window window, RobotModel Robot, RobotRobotOther RobotOther)
        {
            if (DateTime.Now.Hour < 8 || DateTime.Now.Hour > 20) return;
            var orderRecord = contactTasks.OrderByDescending(t => t.SendDate).FirstOrDefault();
            if (orderRecord != null && orderRecord.SendDate > DateTime.Now) return;

            var List = ContactsManage.GetList(Robot, RobotOther);
            List = List.Where(t => !contactTasks.Any(c => c.Key == t.Key)).ToList();
            if (!List.Any()) return;
            var TempList = new List<ContactTask> { List.FirstOrDefault() };
            foreach (var Apply in TempList)
            {
                var ApplyMap = JsonService.ToModel<ContactTask, ContactTaskMap>(Apply);
                ApplyMap.SendDate = DateTime.Now.AddMinutes(10);
                contactTasks.Add(ApplyMap);
                window.FindFirstDescendant(t => t.ByControlType(ControlType.Button).And(t.ByName("通讯录"))).Click(false);
                Thread.Sleep(1000);
                window.FindFirstDescendant(t => t.ByName("清空"))?.Click(false);
                window.FindFirstDescendant(t => t.ByControlType(ControlType.Button).And(t.ByName("添加朋友")))?.Click(false);
                Thread.Sleep(1000);
                var search = window.FindAllDescendants().FirstOrDefault(s => s.Name == "微信号/手机号");
                search.FocusNative();
                search.Focus();
                search.Click();
                var SearchParent = search.Parent;
                if (SearchParent != null)
                {
                    SearchParent.FindFirstDescendant(t => t.ByName("清空"))?.Click();
                    Thread.Sleep(1000);
                    var Search = SearchParent.FindFirstDescendant(s => s.ByControlType(ControlType.Text)).AsTextBox();
                    Search.Text = Apply.Key;
                    var IDS_FAV_SEARCH_RESULT = window.FindFirstDescendant(t => t.ByName("@str:IDS_FAV_SEARCH_RESULT:3780"));
                    AutomationElement Element = IDS_FAV_SEARCH_RESULT.FindFirstDescendant(t => t.ByName("搜索：" + Apply.Key));
                    Thread.Sleep(2000);
                    if (Element != null)
                    {
                        window.CencelTop();

                        Element.Click();
                        Thread.Sleep(2000);
                        var IsCunZai = IDS_FAV_SEARCH_RESULT.FindAllChildren().Any(t => t.Name.Contains("无法找到该用户"));
                        if (IsCunZai)
                        {
                            Console.WriteLine($"Key:{Apply.Key},无法找到该用户");
                            ContactsManage.SendFriend(Robot, Apply, ApplyType.不存在);
                            continue;
                        }
                        window = new MainWindow().GetWindowById();
                        Thread.Sleep(2000);


                        var IsInfo = window.FindFirstDescendant(t => t.ByName("发消息"));
                        if (IsInfo != null)
                        {
                            Console.WriteLine($"Key:{Apply.Key},已是好友");
                            ContactsManage.SendFriend(Robot, Apply, ApplyType.已是好友);
                            continue;
                        }
                        var IsAdd = window.FindFirstDescendant(t => t.ByName("添加到通讯录"));
                        if (IsAdd != null)
                        {
                            Thread.Sleep(5000);
                            var NickName = window.FindAllDescendants(t => t.ByControlType(ControlType.Button)).Where(t => !string.IsNullOrEmpty(t.Name)).FirstOrDefault()?.Name;
                            Apply.NickName = NickName;
                            Console.WriteLine($"Key:{Apply.Key},NickName:{Apply.NickName},可添加");
                            IsAdd.Click();
                            Thread.Sleep(2000);
                            window.FriendApply(Robot, Apply);
                            continue;
                        }
                        ContactsManage.SendFriend(Robot, Apply, ApplyType.添加失败);
                    }
                }
            }


        }
        /// <summary>
        /// 读取好友列表
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void ReadContacts(this Window window, RobotModel Robot, RobotRobotOther RobotOther)
        {
            if (Robot.ReadContactsExpDate > DateTime.Now) return;

            window.FindFirstDescendant(t => t.ByControlType(ControlType.Button).And(t.ByName("通讯录"))).Click(false);
            MainWindowType.Move(120);
            Thread.Sleep(200);
            var IsOver = false;
            List<string> RoomNameKeyList = new List<string>();
            List<RoomModel> RoomModelList = new List<RoomModel>();
            Action action = () =>
            {
                List<string> RoomNameList = new List<string>();
                foreach (var item in window.FindAllDescendants())
                {
                    if (!string.IsNullOrWhiteSpace(item.Name) && item.Parent?.ControlType == ControlType.List && item.Name != "公众号" && item.Name != "订阅号" && item.Name != "新的朋友")
                    {
                        var RoomInfo = window.RoomInfo(item.Name, item, true);
                        RoomModelList.Add(RoomInfo);
                        RoomNameList.Add(RoomInfo.Name);
                    }
                }
                var RoomNameKey = new SignService().SignMD5($"{string.Join(",", RoomNameList)}");
                if (RoomNameKeyList.Any(t => t == RoomNameKey)) IsOver = true;
                RoomNameKeyList.Add(RoomNameKey);
                MainWindowType.Scroll(-1);
            };
            int Count = 0;
            while (!IsOver)
            {
                action();
                Thread.Sleep(2000);
                Console.WriteLine(Count++);
            }
            Console.WriteLine("IsOver" + IsOver);
            var RoomModelListGroup = RoomModelList.GroupBy(t => t.Name);
            List<RoomModel> RoomModelRequestList = new List<RoomModel>();
            foreach (var item in RoomModelListGroup)
            {
                var Name = item.Key;
                var Avatar = item.FirstOrDefault().Avatar;
                RoomModelRequestList.Add(new RoomModel { Avatar = Avatar, Name = Name, });
            }
            Console.WriteLine("RoomModelRequestList" + RoomModelRequestList.Count());
            for (int i = 0; i < RoomModelRequestList.Count(); i += 10)
            {
                ContactsManage.TongBuFriend(Robot, RobotOther, RoomModelRequestList.Skip(i).Take(10).ToList());
            }
            Robot.ReadContactsExpDate = DateTime.Now.AddDays(14);
            new AIJQR().SetRobotModel(Robot);
        }
        public class FriendApplyModel
        {
            public string Name { get; set; }
            public ControlType ControlType { get; set; }
            public string Msg { get; set; }
        }
        /// <summary>
        /// 申请
        /// </summary>
        /// <param name="window"></param>
        /// <param name="Robot"></param>
        /// <param name="Apply"></param>
        public static void FriendApply(this Window window, RobotModel Robot, ContactTask Apply)
        {
            window = new MainWindow().GetWindowById();
            var IsApply = window.FindFirstDescendant(t => t.ByName("申请添加朋友"));
            if (IsApply != null)
            {
                try
                {
                    bool CurrentApply = false;
                    string CurrentApplyName = string.Empty;
                    List<FriendApplyModel> List = new List<FriendApplyModel>
                    {
                    };
                    if (!string.IsNullOrWhiteSpace(Apply.RemarkApply)) List.Add(new FriendApplyModel { Name = "发送添加朋友申请", ControlType = ControlType.Text, Msg = Apply.RemarkApply });
                    if (!string.IsNullOrWhiteSpace(Apply.RemarkApply)) List.Add(new FriendApplyModel { Name = "备注名", ControlType = ControlType.Text, Msg = Apply.RemarkName });
                    if (Apply.BuKanTa) List.Add(new FriendApplyModel { Name = "不看他（她）", ControlType = ControlType.Text, Msg = "" });
                    if (Apply.BuRangTaKan) List.Add(new FriendApplyModel { Name = "不让他（她）看", ControlType = ControlType.Text, Msg = "" });

                    foreach (var item in window.FindAllDescendants())
                    {
                        var Model = List.FirstOrDefault(t => t.Name == item.Name && item.ControlType == ControlType.Text);
                        if (Model != null)
                        {
                            CurrentApply = true;
                            CurrentApplyName = item.Name;
                            continue;
                        }
                        if (item.ControlType == ControlType.Edit && CurrentApply)
                        {
                            CurrentApply = false;
                            var Msg = List.FirstOrDefault(t => t.Name == CurrentApplyName)?.Msg;
                            WechatAuto.ClearEditTextBoxUsingKeyboard(item, Msg);
                            Thread.Sleep(200);
                            continue;
                        }
                        if (item.ControlType == ControlType.CheckBox && CurrentApply)
                        {
                            CurrentApply = false;
                            item?.Click();
                            Thread.Sleep(200);
                            continue;
                        }
                        if (Apply.Tags != null && Apply.Tags.Any() && Apply.Tags.Contains(item.Name) && item.ControlType == ControlType.CheckBox) { item.Click(); Thread.Sleep(1000); continue; }
                        if (Apply.AuthType == AuthType.chat && item.Name == "仅聊天" && item.ControlType == ControlType.CheckBox) { item?.Click(); Thread.Sleep(1000); continue; }
                        if (Apply.AuthType == AuthType.friend && item.Name == "聊天、朋友圈、微信运动等" && item.ControlType == ControlType.CheckBox) { item?.Click(); Thread.Sleep(1000); continue; }
                        if ("确定" == item.Name)
                        {
                            Thread.Sleep(2000);
                            window.FindFirstDescendant(t => t.ByName("确定").And(t.ByControlType(ControlType.Button)))?.Click();
                            ContactsManage.SendFriend(Robot, Apply, ApplyType.已添加);
                            Thread.Sleep(1000);
                            break;
                        }

                    }
                }
                catch (Exception ex)
                {
                    window.FindFirstDescendant(t => t.ByName("取消").And(t.ByControlType(ControlType.Button)))?.Click();
                }
            }
            window.FindFirstDescendant(t => t.ByName("取消").And(t.ByControlType(ControlType.Button)))?.Click();
            Thread.Sleep(1000);

        }

        /// <summary>
        /// 会话消息
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static void EntryRobot(this Window window, RobotModel Robot)
        {
            List<(string, List<MessageRecord>)> qwenList = new List<(string, List<MessageRecord>)> { };
            //请求的ID
            List<(string, DateTime, SENDDATA)> requestIdList = new List<(string, DateTime, SENDDATA)> { };
            while (true)
            {
                //重启应用
                new MainWindow().ResetAppStart();
                //移除一天的数据
                var First = requestIdList.FirstOrDefault(t => t.Item2 < DateTime.Now.AddDays(-1));
                if (!string.IsNullOrWhiteSpace(First.Item1)) requestIdList.Remove(First);

                window = new MainWindow().GetWindowById();
                window.Top();
                //是否处于登录状态
                if (!window.IsLogin())
                {
                    window.Login();
                    continue;
                }
                //属于机器人此值存在
                RobotRobotOther RobotOther = null;
                if (!ConfigManage.Exists(Robot, out RobotOther))
                {
                    if (string.IsNullOrWhiteSpace(Robot.RobotCode))
                    {
                        Robot = window.RobotInfo(RobotOther);
                    }
                    Console.WriteLine($"{DateTime.Now} {Robot.RobotName}:{Robot.RobotCode}:不属于机器人");
                    Thread.Sleep(1000 * 60);
                    continue;
                }
                //是否在休息阶段
                if (!IsWork(window, Robot, RobotOther.RestingStartTime, RobotOther.RestingEndTime, RobotOther.ResetWechat)) continue;

                //添加通讯录
                window.AddContacts(Robot, RobotOther);

                //读取好友列表
                window.ReadContacts(Robot, RobotOther);

                //执行任务
                window.Task(Robot, RobotOther);
                //点击聊天按钮 是否有气泡
                if (!window.IsBubble())
                {
                    //没有气泡时进入自己的页面等待
                    window.JoinCurrentRobot();
                    //是否为转人工，直到转为AI
                    while (window.IsRealUser(Robot, RobotOther)) Thread.Sleep(1000 * 60);

                    Thread.Sleep(GetMillisecondsTimeout(RobotOther));
                    continue;
                }

                //!t.Name.Contains("已置顶") &&
                var WechatMsgList = window.FindAllDescendants().Where(t => t.Parent != null && t.Parent.Name == "会话")
                    .Where(t => !t.Name.Contains("订阅号"))
                    //.Where(t => !t.Name.Contains("已置顶"))
                    .Take(1);// 
                foreach (var WechatMsg in WechatMsgList)
                {
                    if (WechatMsg.BoundingRectangle.X == 0) continue;
                    //是否在聊天种有搜索网络结果
                    window.IsSearchWangGeJieGuo(Robot, RobotOther);
                    WechatMsg?.Click();
                    Thread.Sleep(400);
                    //是否未公众号
                    if (window.IsGongZhongHao()) continue;

                    //WechatMsg.DrawHighlight(System.Drawing.Color.Red);

                    // 返回false 则不需要记录 昨天的数据或者是 条件没有大于=3条
                    if (!window.FindPathText(WechatMsg, out DateTime MsgDateTime)) continue;


                    //获取会话信息
                    window.FindRoomInfo(WechatMsg, out bool IsQun, out int RoomCount, out string RoomName, out string RoomNameOrg);

                    //获取会话头像
                    var RoomInfo = window.RoomInfo(RoomName, WechatMsg);


                    var MsgRight = window.FindAllDescendants().FirstOrDefault(t => t.Name == "消息" && t.ControlType == ControlType.List);
                    if (MsgRight == null) continue;
                    var MsgRightList = MsgRight.FindAllDescendants(t => t.ByControlType(ControlType.ListItem));
                    if (MsgRightList == null || MsgRightList.Count() == 0) continue;
                    var itemMsgInfo = MsgRightList.LastOrDefault();

                    //处理其他消息
                    var itemMsgInfoOther = MsgRightList.ToList().Remove(itemMsgInfo);
                    var MsgRightListCount = MsgRightList.Count();
                    List<string> Last3 = new List<string>();
                    var TopCount = 0;
                    foreach (var item in MsgRightList)
                    {
                        if (TopCount++ + 3 < MsgRightListCount) continue;//只处理三个
                        var ImgUrlOther = string.Empty;
                        var MessageTypeOther = MessagesType.文本.ToString();
                        //if (item.Name == "[图片]"||item.Name == "[语音]") { continue; }
                        //取一个
                        var NickBtnOther = item.FindAllDescendants(t => t.ByControlType(ControlType.Button)).FirstOrDefault(t => !string.IsNullOrWhiteSpace(t.Name));
                        if (NickBtnOther == null) { continue; }

                        var SendNickNameOther = NickBtnOther?.Name;//发送消息人的名称
                        var RoomSendNickNameOther = SendNickNameOther;//发送消息人在群里的名称
                        var IsRobotSendOther = SendNickNameOther == Robot.RobotName;//是否为机器人发送
                        var SendMessageOther = item.Name;//发送的消息
                        if (IsQun && !IsRobotSendOther)
                        {
                            RoomSendNickNameOther = item.FindAllDescendants(t => t.ByControlType(ControlType.Text)).Where(t => t.Name != SendMessageOther).FirstOrDefault()?.Name;//发送消息人在群里的名称
                            if (string.IsNullOrWhiteSpace(RoomSendNickNameOther)) RoomSendNickNameOther = SendNickNameOther;
                        }

                        var SendDataOther = new SENDDATA { Message = SendMessageOther, Messages = SendMessageOther, MsgDate = MsgDateTime, NickName = SendNickNameOther, RoomNickName = RoomSendNickNameOther, RoomName = RoomName, TenantID = RobotOther.TenantID, RobotName = Robot.RobotName, RoomType = IsQun ? "群" : "个人", RoomCount = RoomCount, RobotCode = Robot.RobotCode, RoomNameOrg = RoomNameOrg, ImgUrl = ImgUrlOther, MessageType = MessageTypeOther, HistoryId = "", };
                        //反馈false 不合法需要 continue 退出 处理特殊消息 语音 图片
                        if (!window.OptOtherMsg(MsgRight, NickBtnOther, RobotOther, SendDataOther, IsRobotSendOther, IsQun, ref SendMessageOther, ref MessageTypeOther, ref ImgUrlOther)) continue;

                        var CurrentMessageOther = SendMessageOther;//发送的消息
                        if (string.IsNullOrWhiteSpace(CurrentMessageOther)) continue;
                        if (SendMessageOther.Contains("请先发送朋友验证请求，对方验证通过后，才能聊天")) continue;

                        //发送消息的用户头像
                        var UserInfoOther = window.SendAvatar(RoomName, RoomSendNickNameOther, item.FindAllDescendants(t => t.ByControlType(ControlType.Button)).LastOrDefault());
                        SendDataOther = new SENDDATA { Message = SendMessageOther, Messages = CurrentMessageOther, MsgDate = MsgDateTime, NickName = SendNickNameOther, RoomNickName = RoomSendNickNameOther, RoomName = RoomName, TenantID = RobotOther.TenantID, RobotName = Robot.RobotName, RoomAvatar = RoomInfo.Avatar, MacIP = WinInfo.GetIP(), MacAddress = WinInfo.GetMacAddress(), MacName = WinInfo.GetHostName(), RoomType = IsQun ? "群" : "个人", RoomCount = RoomCount, RobotCode = Robot.RobotCode, NickAvatar = UserInfoOther.Avatar, RoomNameOrg = RoomNameOrg, ImgUrl = ImgUrlOther, MessageType = MessageTypeOther, IsForward = false, HistoryId = "", };
                        //是否已经处理
                        SendDataOther.RequestId = new SignService().SignMD5($"{SendDataOther.Message}{SendDataOther.Messages}{SendDataOther.MsgDate.ToString("yyyyMMddHH")}{SendDataOther.RobotCode}{SendDataOther.RoomName}{SendDataOther.NickName}{SendDataOther.RoomNickName}");
                        //if (requestIdList.Any(t => t.Item1 == SendDataOther.RequestId)) continue;
                        //requestIdList.Add((SendDataOther.RequestId, DateTime.Now, SendDataOther));
                        //Console.WriteLine($"{SendDataOther.MsgDate}===类型：{SendDataOther.RoomType}，名称：【{SendDataOther.RoomNameOrg}】，别名：【{SendDataOther.RoomName}】，数量：【{RoomCount}】===");
                        new LoggerService().RequestMsgDebug(RoomName, RoomSendNickNameOther, SendDataOther);
                        MessageManage.Send(SendDataOther);

                        Last3.Add($"{SendDataOther.RoomNickName}:{SendDataOther.Message}");
                    }




                    var ImgUrl = string.Empty;
                    var MessageType = MessagesType.文本.ToString();
                    var SendNickName = string.Empty;//发送消息人的名称
                    var RoomSendNickName = string.Empty;//发送消息人在群里的名称
                    var IsRobotSend = false;//是否为机器人发送
                    var SendMessage = string.Empty;//发送的消息

                    //取一个
                    var NickBtn = itemMsgInfo.FindAllDescendants(t => t.ByControlType(ControlType.Button)).FirstOrDefault(t => !string.IsNullOrWhiteSpace(t.Name));

                    SendNickName = NickBtn?.Name;//发送消息人的名称
                    RoomSendNickName = SendNickName;//发送消息人在群里的名称
                    IsRobotSend = SendNickName == Robot.RobotName;//是否为机器人发送
                    SendMessage = itemMsgInfo.Name;//发送的消息
                    if (IsQun && !IsRobotSend)
                    {
                        RoomSendNickName = itemMsgInfo.FindAllDescendants(t => t.ByControlType(ControlType.Text)).Where(t => t.Name != SendMessage).FirstOrDefault()?.Name;//发送消息人在群里的名称
                        if (string.IsNullOrWhiteSpace(RoomSendNickName)) RoomSendNickName = SendNickName;
                    }

                    var SendData = new SENDDATA { Message = SendMessage, Messages = SendMessage, MsgDate = MsgDateTime, NickName = SendNickName, RoomNickName = RoomSendNickName, RoomName = RoomName, TenantID = RobotOther.TenantID, RobotName = Robot.RobotName, RoomType = IsQun ? "群" : "个人", RoomCount = RoomCount, RobotCode = Robot.RobotCode, RoomNameOrg = RoomNameOrg, ImgUrl = ImgUrl, MessageType = MessageType, HistoryId = "", };

                    //反馈false 不合法需要 continue 退出 处理特殊消息 语音 图片
                    if (!window.OptOtherMsg(MsgRight, NickBtn, RobotOther, SendData, IsRobotSend, IsQun, ref SendMessage, ref MessageType, ref ImgUrl)) continue;


                    var CurrentMessage = SendMessage;//发送的消息
                    if (string.IsNullOrWhiteSpace(CurrentMessage)) continue;

                    if (SendMessage.Contains("请先发送朋友验证请求，对方验证通过后，才能聊天")) continue;

                    //发送消息的用户头像
                    var UserInfo = window.SendAvatar(RoomName, RoomSendNickName, MsgRight.FindAllDescendants(t => t.ByControlType(ControlType.Button)).LastOrDefault());


                    SendData = new SENDDATA { Message = SendMessage, Messages = CurrentMessage, MsgDate = MsgDateTime, NickName = SendNickName, RoomNickName = RoomSendNickName, RoomName = RoomName, TenantID = RobotOther.TenantID, RobotName = Robot.RobotName, RoomAvatar = RoomInfo.Avatar, MacIP = WinInfo.GetIP(), MacAddress = WinInfo.GetMacAddress(), MacName = WinInfo.GetHostName(), RoomType = IsQun ? "群" : "个人", RoomCount = RoomCount, RobotCode = Robot.RobotCode, NickAvatar = UserInfo.Avatar, RoomNameOrg = RoomNameOrg, ImgUrl = ImgUrl, MessageType = MessageType, IsForward = false, HistoryId = "", };
                    //是否已经处理

                    SendData.RequestId = new SignService().SignMD5($"{SendData.Message}{SendData.Messages}{SendData.MsgDate.ToString("yyyyMMddHH")}{SendData.RobotCode}{SendData.RoomName}{SendData.NickName}{SendData.RoomNickName}");
                    //if (requestIdList.Any(t => t.Item1 == SendData.RequestId)) continue;
                    //requestIdList.Add((SendData.RequestId, DateTime.Now, SendData));

                    //Console.WriteLine($"{SendData.MsgDate}===类型：{SendData.RoomType}，名称：【{SendData.RoomNameOrg}】，别名：【{SendData.RoomName}】，数量：【{RoomCount}】===");
                    new LoggerService().RequestMsgDebug(RoomName, RoomSendNickName, SendData);
                    //记录最后一次聊天
                    MessageManage.Send(SendData);

                    //是否自动回复
                    if (!RobotOther.IsAutoReply) continue;


                    //获取管理的群/个人的配置-返回自动回复的群信息
                    var Config = ConfigManage.GetConifg(RoomName, SendData.RoomType, Robot);
                    if (Config == null) continue;

                    //邀请人通知-欢迎语
                    if (IsQun && window.ShareMessage(Robot, RobotOther, SendMessage, Config.Model.WelcomeMessage, RoomName, RoomCount, RoomInfo.Avatar)) continue;
                    //加好友 个人邀请人通知-欢迎语
                    if (!IsQun && window.AddFriend(Robot, RobotOther, SendMessage, Config, RoomName, RoomInfo.Avatar)) continue;
                    //自己的消息不需要回复
                    if (IsRobotSend) continue;
                    //只有@机器人才可以有回复
                    if (IsQun && !new AIJQR().DataExists(Config.NickNameList, SendMessage)) continue;
                    //费用
                    if (window.FeiYong(Robot, RobotOther, Config, IsQun, RoomName, RoomInfo.Avatar, RoomCount, RoomSendNickName, SendMessage)) continue;
                    //敏感词
                    if (window.MinGanCi(Robot, RobotOther, Config, IsQun, RoomName, RoomInfo.Avatar, RoomCount, RoomSendNickName, SendMessage)) continue;
                    //客服
                    if (window.KeFu(Robot, RobotOther, Config, IsQun, RoomName, RoomInfo.Avatar, RoomCount, RoomSendNickName, SendMessage)) continue;
                    //用户对应此次房间的KEY
                    var RoomNickNameKey = RoomName;
                    if (IsQun) { RoomNickNameKey = RoomName + RoomSendNickName; }
                    var QwenMessage = new AIJQR().DataRemove(Config.NickNameList, SendMessage);
                    if (qwenList.Any(t => t.Item1 == RoomNickNameKey))
                    {
                        var qwenModel = qwenList.FirstOrDefault(t => t.Item1 == RoomNickNameKey);
                        var index = qwenList.IndexOf(qwenModel);
                        qwenModel.Item2.Add(new MessageRecord { Role = RoleType.user.ToString(), Message = QwenMessage });
                        qwenList[index] = qwenModel;
                    }
                    else
                    {
                        qwenList.Add((RoomNickNameKey, new List<MessageRecord> { new MessageRecord { Role = RoleType.user.ToString(), Message = QwenMessage } }));
                    }
                    var MemoryId = string.Empty;
                    if (RobotOther.IsMemory)
                    {
                        MemoryId = ConfigManage.GetMemoryId(RobotOther, Config.Model, Key: RoomNickNameKey, Description: RoomNickNameKey);
                    }

                    {
                        var qwenModel = qwenList.FirstOrDefault(t => t.Item1 == RoomNickNameKey);
                        var qwenModelLast = qwenModel.Item2.LastOrDefault();
                        var ResponseId = qwenModel.Item2.Where(t => !string.IsNullOrWhiteSpace(t.ResponseId)).LastOrDefault()?.ResponseId;
                        if (string.IsNullOrWhiteSpace(Config.Model.ModuleType)) continue;
                        ResponseMessage result = default;
                        if (new AIMouldeType().Exists(Config.Model.ModuleType, MouldeType.bailian))
                        {
                            result = new BaiLianService().Generation(RobotOther, Config.Model, SessionId: ResponseId, MemoryId: MemoryId, qwenModelLast.Message, RoomName);
                        }
                        if (new AIMouldeType().Exists(Config.Model.ModuleType, MouldeType.qianwen))
                        {
                            result = new QWenService().Generation(RobotOther, Config.Model.MouldeKEY, qwenModel.Item2.Take(5).ToList().Select(t => new MessagesItem { role = RoleType.user.ToString(), content = t.Message, }).ToList());
                            //var result = new QWenService().Generation(new List<MessagesItem> { new MessagesItem { role = RoleType.user.ToString(), content = QwenMessage } });
                        }
                        if (!result.Success)
                        {
                            ///无应答
                            SendMessage = string.Join("\n", Last3);
                            window.WuYingDa(Robot, RobotOther, Config, IsQun, RoomName, RoomInfo.Avatar, RoomCount, RoomSendNickName, SendMessage, MessageType);
                            continue;
                        }
                        else
                        {
                            var index = qwenList.IndexOf(qwenModel);
                            qwenModel.Item2.Add(new MessageRecord { Role = result.Role, Message = result.Message, ResponseId = result.ResponseId });
                            qwenList[index] = qwenModel;
                            //处理越界关键词
                            window.YueJie(Robot, RobotOther, Config, IsQun, RoomName, RoomInfo.Avatar, RoomCount, RoomSendNickName, result.Message, MessageType);
                        }
                    }
                }
                Thread.Sleep(200);
            }
        }
    }
}
